package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.query.TravelQuery;
import cn.wolfcode.wolf2w.repository.TravelRepository;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
/**
* 游记服务接口实现
*/
@Service
//@Transactional  现在写不能事务, 需要讲完复制集才能使用事务
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private TravelRepository repsitory;

    @Autowired
    private MongoTemplate template;



    @Override
    public void save(Travel travel) {
        travel.setId(null);
        repsitory.save(travel);
    }

    @Override
    public void update(Travel travel) {
        repsitory.save(travel);
    }

    @Override
    public void delete(String id) {
        repsitory.deleteById(id);
    }

    @Override
    public Travel get(String id) {
        return repsitory.findById(id).orElse(null);
    }

    @Override
    public List<Travel> list() {
        return repsitory.findAll();
    }

    @Override
    public Page<Travel> query(TravelQuery qo) {
        Query query = new Query();
        Pageable pageable = PageRequest.of(qo.getCurrentPage()- 1,qo.getPageSize(), Sort.Direction.ASC, "_id");
        return DBHelper.query(template,pageable, query,Travel.class, qo);
    }

    @Override
    public void saveOrUpdate(Travel travel) {
        if(StringUtils.hasLength(travel.getId())){
            //update
            this.update(travel);
        }else{
            //save
            this.save(travel);
        }
    }
}
